package model;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class DAOJPA<T> {
	private static EntityManager manager;
	private Class<T> type = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];

	protected DAOJPA(){ 
		manager = getManager();
	}
	protected static EntityManager getManager(){
		if(manager==null){
			EntityManagerFactory factory = Persistence.createEntityManagerFactory("piollin");
			manager = factory.createEntityManager();
		}
		return manager;
	}
		
	public void persist(T obj){
		getManager().persist(obj);
	}
	public void merge(T obj){
		getManager().merge(obj);
	}
	public void remove(T obj) {
		getManager().remove(obj);
	}
	public T find(Object chave) {
		return (T)getManager().find(type, chave);
	}
	public List<T> findALL() {
		
		Query q = getManager().createQuery("select x from " + type.getSimpleName()  + " x");
		
		return q.getResultList();
	}
	
	public void removerPorId (String classe, int id)
		{
			Query q = getManager().createQuery("delete from "+ classe +" c where c.id="+ id);
			q.executeUpdate();
		}
	public List<Object> findAllByClass(String classe)
		{
			Query q = getManager().createQuery("select o from "+ classe +" o" );
			return q.getResultList();
		}
	
	public void begin(){
		getManager().getTransaction().begin();
	}
	public void commit(){
		getManager().getTransaction().commit();
	}
	public void rollback(){
		getManager().getTransaction().rollback();
	}
}
